package bma.common.langutil.jmshell.common;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import bma.common.langutil.jmshell.Session;
import bma.common.langutil.jmshell.SessionCloseListener;

public abstract class AbstractSession implements Session {

	protected String id;
	protected Map<String, Object> attributes = Collections
			.synchronizedMap(new HashMap<String, Object>());
	protected List<SessionCloseListener> listeners = Collections
			.synchronizedList(new ArrayList<SessionCloseListener>());

	public AbstractSession() {
		super();
	}

	@Override
	public String getId() {
		return id;
	}

	@Override
	public Object getAttribute(String name) {
		return attributes.get(name);
	}

	@Override
	public Set<String> getAttributeNames() {
		return new HashSet<String>(attributes.keySet());
	}

	@Override
	public void setAttribute(String name, Object value) {
		attributes.put(name, value);
	}

	@Override
	public void removeAttribute(String name) {
		attributes.remove(name);
	}

	@Override
	public void clearAttributes() {
		attributes.clear();
	}

	@Override
	public boolean writeln(String msg) {
		return write(msg + "\n");
	}

	@Override
	public void addCloseListener(SessionCloseListener lis) {
		listeners.add(lis);
	}

	protected void invokeClose() {
		List<SessionCloseListener> tmp = new ArrayList<SessionCloseListener>(
				listeners);
		listeners.clear();
		for (SessionCloseListener lis : tmp) {
			lis.onClose(this);
		}
	}

	@Override
	public void removeCloseListener(SessionCloseListener lis) {
		listeners.remove(lis);
	}
}
